import { getUserAuth } from "@/api/account"
import { matchRouter } from "@/utils"
import { asyncRouter, empty } from "@/router/index"
const state = {
    asyncRouter: [],
    buttonList: [],
    menuList: [],
    admin: false,
};
const getters = {}
const mutations = {
    SET_ADMIN(state, value){
        state.admin = value
    },
    SET_MENU_AUTH(state, value){
        state.menuList = value
        console.log('state.menuList', state.menuList)
    },
    SET_BUTTON_AUTH(state, value){
        state.buttonList = value
    },
    SET_ASYNC_ROUTER(state, value){
        state.asyncRouter = value.concat(empty)
        console.log('state.asyncRouter', state.asyncRouter)
    }
}
const actions = {
    activeGetAuth(prams){
        return new Promise((resolve, reject) => {
            getUserAuth().then(res => {
                /**
                 * 按钮权限
                 */
                // 非超管
                const button = res.content?.buttonList || null
                const menu = res.content?.menuList || null
                const buttonKey =  button ? button.map(item => item.router_key) : []
                const menuKey =  menu ? menu.map(item => item.router_path) : []
                prams.commit('SET_BUTTON_AUTH', buttonKey)
                prams.commit('SET_MENU_AUTH', menuKey)
                // 超管
                const admin = res.content?.admin || false
                prams.commit('SET_ADMIN', admin)
                /**
                 * 菜单权限，过滤
                 */
                if(admin) {
                    prams.commit('SET_ASYNC_ROUTER', asyncRouter)
                    resolve(asyncRouter)
                }else{
                    const menuRouter = matchRouter(asyncRouter, menuKey)
                    prams.commit('SET_ASYNC_ROUTER', menuRouter)
                    resolve(menuRouter)
                }
                
            })
        })
    }
}

export default {
    namespaced: true,
    state,
    getters,
    mutations,
    actions
};